package com.flyme.common.prism.api;

import com.flyme.common.http.HttpClientUtil;
import com.flyme.common.http.UrlConstants;
import com.flyme.common.utils.base.PropertiesUtil;
import com.flyme.common.utils.collection.ListUtil;
import com.flyme.common.utils.collection.MapUtil;
import com.flyme.common.utils.mapper.JsonMapper;
import com.flyme.common.utils.text.EncodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 *
 */
public class PrismOperationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PrismOperationService.class);

    private static JsonMapper mapper = JsonMapper.nonNullMapper();
    private static final String RESOURCE_PROPERTIES_NAME = "/resource.properties";
    private static String PRISM_URL_REF_ID = "maven.registerCenter.url";

    private static int DEFAULT_CONNECTIONTIMEOUT = -1;
    private static int DEFAULT_READTIMEOUT = -1;

    private String prismBaseUrl;
    private String username = "yanxin.li";
    private String password = new String(EncodeUtil.decodeBase64("UVdFUnF3ZXIxMTA="));
    private String userType = "ucarinc";

    public PrismOperationService() {
        Properties properties = PropertiesUtil.loadFromFile(PrismOperationService.class.getResource(RESOURCE_PROPERTIES_NAME).getPath());
        prismBaseUrl = PropertiesUtil.getString(properties, PRISM_URL_REF_ID, "http://prismtest.10101111.com/prism");
        initLogin();
    }

    private void initLogin() {
        if (StringUtils.isBlank(prismBaseUrl)) {
            return;
        }
        Map<String, String> param = MapUtil.newHashMap(new String[]{"userName", "password", "userType"},
                new String[]{username, password, userType});
        String loginRes = HttpClientUtil.sendHttpPost(prismBaseUrl + UrlConstants.LOGIN_URL, param);

        if (StringUtils.isNotBlank(loginRes)) {
            Map<String, Object> loginMap = mapper.fromJson(loginRes, mapper.buildMapType(HashMap.class, String.class, Object.class));

            if ((Boolean) loginMap.get("ret")) {
                Map<String, String> envChangeParam = MapUtil.newHashMap("code", "uc");
                String envChangeParamValue = HttpClientUtil.convertStringParameter(envChangeParam);
                String envChangeRes = HttpClientUtil.sendHttpGet(prismBaseUrl + UrlConstants.ENV_CHANGE_URL + "?" + envChangeParamValue);

                if (StringUtils.isNotBlank(envChangeRes)) {
                    Map<String, Object> envChangeMap = mapper.fromJson(envChangeRes, mapper.buildMapType(HashMap.class, String.class, Object.class));
                    if ((Boolean) envChangeMap.get("ret")) {
                        LOGGER.info("change env success...");
                    }
                }
            } else {
                LOGGER.info("login error...");
            }
        }
    }

    /**
     * 判断服务是否存在
     *
     * @param serviceName
     * @return
     */
    public ServiceModel exist(String serviceName) {
        Map<String, String> param = MapUtil.newHashMap(new String[]{"draw", "start", "length", "serviceName"},
                new String[]{"3", "0", "10", serviceName});
        String paramValue = HttpClientUtil.convertStringParameter(param);
        String res = HttpClientUtil.sendHttpGet(prismBaseUrl + UrlConstants.SEARCH_SERVICE_URL + "?" + paramValue);
        if (StringUtils.isNotBlank(res)) {
            SearchResult result = JsonMapper.nonNullMapper().fromJson(res, SearchResult.class);
            if (result.getRecordsTotal() >= 1) {
                return ListUtil.getFirst(result.getData());
            }
        }
        return null;
    }

    /**
     * String serviceName, String beanId, String methodName, int needResult, String serviceDesc
     *
     * @return
     */
    public boolean add(ServiceModel service) {
        Map<String, String> param = MapUtil.newHashMap(new String[]{"registerId", "name", "beanId", "connectionTimeOut", "readTimeOut",
                "methodName", "needResult", "descipt", "loadZk"}, new String[]{"0", service.getName(), service.getBeanId(), String.valueOf(DEFAULT_CONNECTIONTIMEOUT), String.valueOf(DEFAULT_READTIMEOUT),
                service.getMethodName(), String.valueOf(service.getNeedResult()), service.getDescipt(), String.valueOf(true)});
        String paramValue = HttpClientUtil.convertStringParameter(param);
        String res = HttpClientUtil.sendHttpGet(prismBaseUrl + UrlConstants.ADD_SERVICE_URL + "?" + paramValue);
        if (StringUtils.isNotBlank(res)) {
            Map<String, Object> addResMap = mapper.fromJson(res, mapper.buildMapType(HashMap.class, String.class, Object.class));
            if ((Boolean) addResMap.get("ret")) {
                return true;
            }
        }
        return false;
    }

    /**
     * Long registerId, String serviceName, String beanId, String methodName, int needResult, String serviceDesc
     *
     * @return
     */
    public boolean update(ServiceModel service) {
        Map<String, String> param = MapUtil.newHashMap(new String[]{"registId", "name", "beanId", "connectionTimeOut", "readTimeOut",
                "methodName", "needResult", "descipt", "loadZk"}, new String[]{String.valueOf(service.getRegistId()), service.getName(),
                service.getBeanId(), String.valueOf(DEFAULT_CONNECTIONTIMEOUT),
                String.valueOf(DEFAULT_READTIMEOUT), service.getMethodName(), String.valueOf(service.getNeedResult()), service.getDescipt(), String.valueOf(true)});
        String paramValue = HttpClientUtil.convertStringParameter(param);
        String res = HttpClientUtil.sendHttpGet(prismBaseUrl + UrlConstants.UPDATE_SERVICE_URL + "?" + paramValue);
        if (StringUtils.isNotBlank(res)) {
            Map<String, Object> addResMap = mapper.fromJson(res, mapper.buildMapType(HashMap.class, String.class, Object.class));
            if ((Boolean) addResMap.get("ret")) {
                return true;
            }
        }
        return false;
    }
}
